package com.kyle.utils;

import com.google.gson.Gson;
import com.kyle.exceptions.GraceException;
import com.kyle.grace.result.ResponseStatusEnum;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.sql.Date;
import java.util.Base64;

/**
 * @Author：kyle_fu
 * @description: TODO
 * @Date：2024/5/26 21:51
 * @version: 1.0
 */
@Component
@Slf4j
public class JWTUtils {

    public static final String at = "@";

    @Autowired
    private JWTProperties jwtProperties;

    public String createJWTWithPrefix(String stuJson,Long expireTimes,String prefix) {
        if (expireTimes == null){
            GraceException.display(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        }
        return prefix + at + createJWT(stuJson,expireTimes);
    }
    public String createJWTWithPrefix(String stuJson,String prefix) {
        return prefix + at + createJWT(stuJson);
    }

    public String createJWT(String stuJson) {
       return dealJWT(stuJson,null);
    }

    public String createJWT(String stuJson,Long expireTimes) {
        if (expireTimes == null){
            GraceException.display(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        }
        return dealJWT(stuJson,expireTimes);
    }
    public String dealJWT(String stuJson,Long expireTimes) {

        String userKey = jwtProperties.getKey();

        // 1. 对秘钥进行base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        String base64 = encoder.encodeToString(userKey.getBytes());

        // 2. 对base64生成一个秘钥的对象
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());

        String jwt = "";
        if (expireTimes != null) {
            jwt = generateJwt(stuJson,expireTimes,secretKey);
        }else {
            jwt = generateJwt(stuJson,secretKey);
        }
        log.info("JWTUtils_dealJWT:generateJwt = " + jwt);
        return jwt;
    }

    public String generateJwt(String stuJson,SecretKey secretKey) {
        String jwtToken = Jwts.builder()
                .setSubject(stuJson)
                .signWith(secretKey)
                .compact();

        return jwtToken;
    }

    public String generateJwt(String stuJson,Long expireTimes,SecretKey secretKey) {
        Date expirDate = new Date(System.currentTimeMillis() + expireTimes);
        String jwtToken = Jwts.builder()
                .setSubject(stuJson)
                .signWith(secretKey)
                .setExpiration(expirDate)
                .compact();

        return jwtToken;
    }

}
